package com.fingersoft.feature.signpad

import com.google.gson.Gson
import com.google.gson.stream.JsonReader
import com.lzy.okgo.callback.AbsCallback
import okhttp3.Response
import okhttp3.ResponseBody
import java.lang.reflect.Type

abstract class JsonCallback<T> private constructor() : AbsCallback<T>() {

    private var type: Type? = null
    private var clazz: Class<T>? = null

    constructor(type: Type? = null, clazz: Class<T>? = null) : this() {
        this.type = type
        this.clazz = clazz
    }

    /**
     * 拿到响应后，将数据转换成需要的格式，子线程中执行，可以是耗时操作
     *
     * @param response 需要转换的对象
     * @return 转换后的结果
     * @throws Exception 转换过程发生的异常
     */
    override fun convertSuccess(response: Response?): T? {
        val body: ResponseBody? = response?.body() ?: return null

        var data: T? = null
        val gson = Gson()
        val jsonReader = JsonReader(body!!.charStream())
        if (type != null) data = gson.fromJson(jsonReader, type);
        if (clazz != null) data = gson.fromJson(jsonReader, clazz);
        return data;
    }


}